<script setup>
import { fetchDealerGoodsStoreList } from '@/api/goods'
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'
import ViewHTML from '@/components/ViewHTML.vue'

// 控制对话框显示
const previewVisible = ref(false)
const previewContent = ref('')

// 表格数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 查询条件
const queryFields = ref({
  goodsName: '',
})

// 获取商品库存列表数据
const fetchStoreData = async () => {
  try {
    loading.value = true
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      queryFields: {
        goodsName: queryFields.value.goodsName.trim() || null,
      },
    }
    const res = await fetchDealerGoodsStoreList(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取商品库存列表失败')
    }
  } catch (error) {
    logger.error('获取商品库存列表失败', error)
    ElMessage.error('获取商品库存列表失败')
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchStoreData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchStoreData()
}

// 搜索商品库存
const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置为第一页
  fetchStoreData()
}

// 重置搜索条件
const resetSearch = () => {
  queryFields.value.goodsName = ''
  currentPage.value = 1
  fetchStoreData()
}

// 预览商品介绍
const previewIntroduce = (content) => {
  previewContent.value = content
  previewVisible.value = true
}

onMounted(() => {
  fetchStoreData()
})
</script>

<template>
  <el-dialog
    v-model="previewVisible"
    title="商品介绍预览"
    width="40%"
    align-center
    destroy-on-close
  >
    <ViewHTML :content="previewContent" />
  </el-dialog>

  <div class="main-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="queryFields" @submit.prevent="handleSearch">
          <el-form-item label="商品名称">
            <el-input
              v-model="queryFields.goodsName"
              placeholder="请输入商品名称"
              clearable
              style="width: 240px"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="table-container">
      <el-table v-loading="loading" :data="tableData">
        <el-table-column label="商品图片" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.goodsPicture"
              :src="row.goodsPicture"
              style="width: 60px; height: 60px; border-radius: 4px"
              :preview-src-list="[row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
            <div v-else class="no-image">无图片</div>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" show-overflow-tooltip min-width="180" align="center">
          <template #default="{ row }">
            {{ row.goodsName || '' }}
          </template>
        </el-table-column>
        <el-table-column label="规格" min-width="80" align="center">
          <template #default="{ row }">
            <el-tag type="success">{{ row.specifications || '' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="起始有效期"
          prop="periodStartingDate"
          min-width="150"
          align="center"
        />
        <el-table-column label="结束有效期" prop="periodEndDate" min-width="150" align="center" />
        <el-table-column prop="quantity" label="库存数量" min-width="100" align="center" />
        <el-table-column prop="unitPrice" label="单价（元）" min-width="100" align="center" />
        <el-table-column prop="unit" label="单位" min-width="100" align="center" />
        <el-table-column prop="shippingFee" label="配送费（元）" min-width="120" align="center">
          <template #default="{ row }">
            {{ row.shippingFee || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="freeShipping" label="免配送费数量" min-width="130" align="center">
          <template #default="{ row }">
            {{ row.freeShipping || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="isSale" label="是否上架" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isSale ? 'success' : 'danger'">
              {{ row.isSale ? '已上架' : '未上架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="商品介绍" width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" circle @click="previewIntroduce(row.introduce)">
              <template #icon>
                <el-icon><LineMdWatchLoop /></el-icon>
              </template>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="notes" label="备注" min-width="150" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .controller-container {
    border-radius: 10px;
    background-color: #fff;

    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;
    gap: 10px;

    .el-table {
      flex: 1;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
